/**
 * 缓存管理工具
 */

const sessionCache = {
  set(key: string, value: any) {
    if (value === null || value === undefined) {
      sessionStorage.removeItem(key);
    } else {
      sessionStorage.setItem(key, JSON.stringify(value));
    }
  },
  
  get(key: string) {
    const value = sessionStorage.getItem(key);
    if (value === null) {
      return null;
    }
    try {
      return JSON.parse(value);
    } catch {
      return value;
    }
  },
  
  setJSON(key: string, value: any) {
    sessionStorage.setItem(key, JSON.stringify(value));
  },
  
  getJSON(key: string) {
    const value = sessionStorage.getItem(key);
    if (value === null) {
      return null;
    }
    try {
      return JSON.parse(value);
    } catch {
      return null;
    }
  },
  
  remove(key: string) {
    sessionStorage.removeItem(key);
  },
  
  clear() {
    sessionStorage.clear();
  },
};

const localCache = {
  set(key: string, value: any) {
    if (value === null || value === undefined) {
      localStorage.removeItem(key);
    } else {
      localStorage.setItem(key, JSON.stringify(value));
    }
  },
  
  get(key: string) {
    const value = localStorage.getItem(key);
    if (value === null) {
      return null;
    }
    try {
      return JSON.parse(value);
    } catch {
      return value;
    }
  },
  
  setJSON(key: string, value: any) {
    localStorage.setItem(key, JSON.stringify(value));
  },
  
  getJSON(key: string) {
    const value = localStorage.getItem(key);
    if (value === null) {
      return null;
    }
    try {
      return JSON.parse(value);
    } catch {
      return null;
    }
  },
  
  remove(key: string) {
    localStorage.removeItem(key);
  },
  
  clear() {
    localStorage.clear();
  },
};

export default {
  session: sessionCache,
  local: localCache,
};

